<?php
include_once('config/config.php');
$auth = check_auth();
include_once('./config/logout.php');
if (!$_GET['id']) {
    // var_dump($_GET['id']);
    showMsg('该员工不存在');
    exit;
} else {
    $id = $_GET['id'] ?? '';
    // var_dump($id);
    $personSql = "SELECT * FROM `pre_person` WHERE `id` = '$id'";
    $personData = find($personSql);
    // var_dump($personData['avatar']);
}

if ($_POST) {
    // 接收参数
    $name = trim($_POST['name']) ?? '';
    $mobile = trim($_POST['mobile']) ?? '';
    $email = trim($_POST['email']) ?? '';
    $gender = trim($_POST['gender']) ?? '';
    $address = trim($_POST['address']) ?? '';
    $depid = trim($_POST['depid']) ?? '';
    $jobid = trim($_POST['jobid']) ?? '';
    $code = trim($_POST['code']) ?? '';
    // var_dump($code);
    // exit;
    if (empty($name)) {
        showMsg('姓名不能为空');
    }

    if (empty($mobile)) {
        showMsg('手机号不能为空');
    }

    // 判断手机号格式是否正确
    $mobileReg = '/^1[3456789]\d{9}$/';

    preg_match($mobileReg, $mobile, $mobileResult);

    if (empty($mobileResult)) {
        showMsg('手机号格式错误');
    }

    if (empty($email)) {
        showMsg('邮箱不能为空');
    }

    if (empty($address)) {
        showMsg('地址不能为空');
    }

    // 查询部门是否存在
    $depSql = "SELECT * FROM `pre_dep` WHERE `id` = '$depid'";

    $depInfo = find($depSql);

    if (!$depInfo) {
        showMsg('部门不存在');
    }

    // 查询职位
    $jobSql = "SELECT * FROM `pre_job` WHERE `id` = '$jobid'";

    $jobInfo = find($jobSql);

    if (!$jobInfo) {
        showMsg('职位不存在');
    }
    // 不修改手机号时直接储存旧手机号
    if ($mobile != $personData['mobile']) {
        $oldMobile = $personData['mobile'];

        $mobileSql = "SELECT `mobile` FROM `pre_person` WHERE `mobile` != '$oldMobile'";

        $mobileList = finds($mobileSql);

        $mobileRes = false;

        foreach ($mobileList as $item) {
            if ($item['mobile'] == $mobile) {
                $mobileRes = true;
                break;
            }
        }

        if ($mobileRes === true) {
            showMsg('手机号已存在');
        }
    }
    // 不修改邮箱时直接储存旧邮箱
    if ($email != $personData['email']) {
        $oldEmail = $personData['email'];

        $emailSql = "SELECT `email` FROM `pre_person` WHERE `email` != '$oldEmail'";

        $emailList = finds($emailSql);

        $emailStatus = false;

        foreach ($emailList as $item) {
            if ($item['email'] == $email) {
                $emailStatus = true;
                break;
            }
        }

        if ($emailStatus === true) {
            showMsg('邮箱已存在');
        }
    }
    $data = [
        'name' => $name,
        'mobile' => $mobile,
        'email' => $email,
        'gender' => $gender,
        'address' => $address,
        'depid' => $depid,
        'jobid' => $jobid,
        // 'createtime' => time()
    ];

    // 处理地区数据
    $regionSql = "SELECT `parentpath` FROM `pre_region` WHERE `code` = '$code'";

    $parentpath = find($regionSql);

    if (empty($parentpath)) {
        showMsg('所选地区不存在');
    }

    $pathArr = explode(',', $parentpath['parentpath']);

    $data['province'] = $pathArr[0] ?? '';
    $data['city'] = $pathArr[1] ?? '';
    $data['district'] = $pathArr[2] ?? '';

    // 头像
    if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
        $res = build_upload('avatar');

        if ($res['code'] === 0) {
            showMsg($res['msg']);
        }

        $data['avatar'] = $res['data'];
    }


    // 更新数据表
    $result = update('person', $data,"`id` = '$id'");

    if ($result['code'] === 1) {
        if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
            @is_file('.' . $personData['avatar']) && @unlink('.' . $personData['avatar']);
        }

        showMsg('更新成功', 'personList.php');
    } else {
        if(isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0)
        {
            @is_file('.' . $data['avatar']) && @unlink('.' . $data['avatar']);
        }
        showMsg('更新失败');
    }
}

$depSql = "SELECT * FROM `pre_dep` ORDER BY `id` DESC";

$depData = finds($depSql);
// var_dump($depData);
// exit;
$depid = $personData['depid'] ?? '';

$jobSql = "SELECT * FROM `pre_job` WHERE `depid` = '$depid'";

$jobData = finds($jobSql);

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <?php include_once('common/meta.php'); ?>
    <link rel="stylesheet" href="./assets/lib/city-picker/city-picker.css">
</head>

<body>

    <?php include_once('common/header.php'); ?>

    <?php include_once('common/menu.php'); ?>

    <div class="content">
        <div class="header">
            <h1 class="page-title">添加员工</h1>
        </div>
        <ul class="breadcrumb">
            <li><a href="index.php">Home</a> <span class="divider">/</span></li>
            <li class="active">Index</li>
        </ul>

        <div class="container-fluid">
            <div class="row-fluid">

                <div class="btn-toolbar">
                    <button class="btn btn-primary" onClick="location='personList.php'"><i class="icon-list"></i> 员工列表</button>
                    <div class="btn-group">
                    </div>
                </div>

                <div class="well">
                    <div id="myTabContent" class="tab-content">
                        <div class="tab-pane active in" id="home">
                            <form method="post" enctype="multipart/form-data">

                                <label>姓名</label>
                                <input type="text" name="name" id="name" class="input-xxlarge">

                                <label>手机号</label>
                                <input type="text" name="mobile" id="mobile" class="input-xxlarge">

                                <label>邮箱</label>
                                <input type="email" name="email" id="email" class="input-xxlarge">

                                <label>性别</label>
                                <select name="gender" id="gender" class="input-xlarge">
                                    <option value="0">保密</option>
                                    <option value="1">男</option>
                                    <option value="2">女</option>
                                </select>

                                <div class="input-xlarge" style="position: relative;height:60px;margin-bottom:5px;">
                                    <label>地区</label>
                                    <input type="text" id="region" readonly data-toggle="city-picker" value="<?php echo $personData['district'] ? $personData['district'] : ($personData['city'] ? $personData['city'] : $personData['province']); ?>" class="input-xxlarge">
                                    <input type="hidden" name="code" id="code" value="<?php echo $personData['district'] ? $personData['district'] : ($personData['city'] ? $personData['city'] : $personData['province']); ?>">
                                </div>

                                <label>地址</label>
                                <input type="text" id="address" name="address" class="input-xxlarge">

                                <label>部门</label>
                                <select name="depid" id="depid" class="input-xlarge">
                                    <option value="0">请选择</option>
                                    <?php foreach ($depData as $item) { ?>
                                        <option value="<?php echo $item['id']; ?>" <?php echo $item['id'] == $personData['depid'] ? 'selected' : '' ?>><?php echo $item['name']; ?></option>
                                    <?php } ?>

                                </select>

                                <label>职位</label>
                                <select name="jobid" id="jobid" class="input-xlarge">
                                    <option value="0">请选择</option>
                                    <?php foreach ($jobData as $item) { ?>
                                        <option value="<?php echo $item['id']; ?>" <?php echo $item['id'] == $personData['jobid'] ? 'selected' : '' ?>><?php echo $item['name']; ?></option>
                                    <?php } ?>
                                </select>

                                <label>头像</label>
                                <img style="width: 200px;height: 200px;" id="upload" src="<?php echo is_file('.' . $personData['avatar'] ? $personData['avatar'] : './assets/images/avatar.png') ?>" alt="">
                                <input type="file" hidden name="avatar" id="avatar">

                                <label></label>
                                <input class="btn btn-primary" type="submit" value="提交" />
                            </form>
                        </div>
                    </div>
                </div>

                <?php include_once('common/footer.php'); ?>

            </div>
        </div>
    </div>

</body>

</html>
<?php include_once('common/script.php'); ?>
<script src="./assets/lib/city-picker/city-picker.data.min.js"></script>
<script src="./assets/lib/city-picker/city-picker.min.js"></script>

<script>
    // 模拟点击上传框
    $('#upload').click(function() {
        $('#avatar').click();
    });

    // 监听上传框的值是否有变化
    $('#avatar').change(function() {
        let file = $(this)[0].files[0];

        if (file) {
            let Reader = new FileReader();

            Reader.readAsDataURL(file);

            Reader.onload = function() {
                $('#upload').attr('src', Reader.result);
            }
        }
    });
    // personAjax();
    // 当选择部门后触发查询该部门的相应职位
    $('select[name="depid"]').change(function personAjax() {
        // 获取部门id
        let depid = $(this).val();
        $.ajax({
            type: 'post',
            url: 'api.php',
            data: {
                depid,
                action: 'get_job',
            },
            dataType: 'json',
            success: function(res) {
                let tmp = '';

                if (res && res.code === 1) {
                    for (let item of res.data) {
                        tmp += `<option value="${item.id}">${item.name}</option>`
                    }

                } else {
                    tmp = `<option value="0">${res.msg}</option>`
                }

                $('select[name="jobid"]').html(tmp);
            }
        });
    });
    // $("#region").on("cp:updated", function() {
    //     var citypicker = $(this).data("citypicker");
    //     var code = citypicker.getCode("district") || citypicker.getCode("city") || citypicker.getCode("province");
    //     $("#code").val(code);
    // });
    // 信息录入
    // $('#depid').val(1);
    async function personMsg() {
        $('#name').val('<?php echo $personData['name']; ?>');
        $('#mobile').val('<?php echo $personData['mobile']; ?>');
        $('#email').val('<?php echo $personData['email']; ?>');
        $('#gender').val('<?php echo $personData['gender']; ?>');
        $('#address').val('<?php echo $personData['address']; ?>');
        $('#upload').attr('src', '<?php echo '.' . $personData['avatar']; ?>');

    }
    personMsg();
</script>